#include"func.h"
int main(int argc,char* argv[]){
    // ./6_agent_two 1.pipe 2.pipe
    // 1.pipe写端，2.pipe读端
    ARGS_CHECK(argc,3);
    int fdw = open(argv[1],O_WRONLY);
    ERROR_CHECK(fdw,-1,"write error");
    int fdr = open(argv[2],O_RDONLY);
    ERROR_CHECK(fdr,-1,"read error");

    printf("agent_two is connected\n");

    char buf[1024];
    fd_set rdset;//监听集合

    while(1){
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(fdr,&rdset);
        select(fdr+1,&rdset,NULL,NULL,NULL);
        if(FD_ISSET(fdr,&rdset)){
            //如果1.pipe被写端写入了数据，在这接收数据
            memset(buf,0,sizeof(buf));
            ssize_t res = read(fdr,buf,sizeof(buf));
            printf("buf = %s\n",buf);
            //说明此时写端已经退出了，我这里也可以断开了
            if(res==0){
                printf("the connection is error\n");
                break;
            }
        }
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            //如果从标准输入当中获取到了数据，说明该进行要写管道了
            memset(buf,0,sizeof(buf));
            ssize_t res = read(STDIN_FILENO,buf,sizeof(buf));
            //人为停止ctrl+d
            if(res == 0){
                printf("the connection ending\n");
                break;
            }
            write(fdw,buf,strlen(buf));
        }
    }
}
